﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
using IBll;
using Model;
using Model.DtoModel;
using Model.ViewModel;

namespace Bll
{
    public partial class UserInfoBll:IUserInfoBll
    {

        public MessageModel Login(LoginViewModel viewModel)
        {
            MessageModel messageModel=new MessageModel();

            UserInfo userInfo =
                DbSession.IUserInfoDal.GetListBy(m => m.uLoginName == viewModel.uLoginName).FirstOrDefault();
            if ( userInfo== null)
            {
                messageModel.IsSuccess = false;
                messageModel.Message = "用户名不存在";
                return messageModel;
            }
            //MD5
            if (!userInfo.uPwd.Equals(DESEncryptorHelper.Encrypt(viewModel.uPwd)))
            {
                messageModel.IsSuccess = false;
                messageModel.Message = "密码错误";
                return messageModel;
            }
            messageModel.Data = userInfo.ToPoco();
            return messageModel;
        }

        public IQueryable<Permission> GetUserPermission(int uid)
        {
            IQueryable<Permission> listPermissions = from user in DbSession.IUserInfoDal.GetAll()
                                                     join userRole in DbSession.IUserRoleDal.GetAll() on user.uId equals userRole.urUId
                                                     join role in DbSession.IRoleDal.GetAll() on userRole.urRId equals role.rId
                                                     join rolePermission in DbSession.IRolePermissionDal.GetAll() on role.rId equals rolePermission.rpRId
                                                     join permission in DbSession.IPermissionDal.GetAll() on rolePermission.rpPId equals permission.pid
                                                     where user.uId == uid
                                                     orderby permission.pid
                                                     select permission;
            IQueryable<Permission> listVip = from userInfo in DbSession.IUserInfoDal.GetAll()
                                             join userVipPermission in DbSession.IUserVipPermissionDal.GetAll() on userInfo.uId equals
                                                 userVipPermission.vipUserId
                                             join permition in DbSession.IPermissionDal.GetAll() on userVipPermission.vipId equals permition.pid
                                             where userInfo.uId == uid
                                             orderby permition.pid
                                             select permition;
            listPermissions=listPermissions.Union(listVip);
            
            return listPermissions;
        }
    }
}
